import cloud from '@lafjs/cloud'
let userId //用户id
let dbName = "web-order"
let out_trade_no
import { changeStudentSource } from "@/admin/web/set_student_info";

export default async function (ctx: FunctionContext) {
  out_trade_no = generateOrderNumber()

  if (cloud.utils.isString(ctx.user.uid)) {
    userId = ctx.user.uid
  } else {
    userId = ctx.user.uid._id
  }

  let year = cloud.utils.dateTimeFormat(Date.now(), "year")
  let whereJson = {
    userId,
    curriculum_id: ctx.body.curriculum_id,
    _add_time_str: { $regex: year.toString(), $options: "i" }
  }

  let res = await cloud.nw.db.findByWhereJson({
    dbName,
    whereJson,
  });
  if (res && res._id) return cloud.utils.requestReturn({ code: 500, msg: "该课程已报名,请勿重复报名" });

  let { type } = await cloud.nw.db.findByWhereJson({
    dbName: "web-course",
    whereJson: { _id: ctx.body.curriculum_id },
  });

  let resp = await cloud.nw.db.findByWhereJson({
    dbName: "web-curriculum",
    whereJson: { _id: type[0] },
  });

  let status
  if (resp.hasOwnProperty("isExamine") && resp.isExamine == 1) {  //需要审核
    status = 1
  } else {
    status = 2  //报名成功
  }

  let dataJson = {
    ...ctx.body,
    out_trade_no,
    userId,
    status
  }
  await cloud.nw.db.add({
    dbName, dataJson, cancelAddTime: false
  });
  changeStudentSource(out_trade_no); // 改变学生来源
  return cloud.utils.requestReturn({ data: "" })
}

// 生成订单号
function generateOrderNumber() {
  const timestamp = Date.now().toString(); // 获取当前时间戳
  const random = Math.floor(Math.random() * 1000).toString().padStart(3, '0'); // 生成3位随机数
  return timestamp + random; // 拼接时间戳和随机数作为订单号
}